#include "GPU_Handler.h"

GPU_Handler gpu;

int width=300, height=300;

float* data;
float* result;


void display()
{

	gpu.FBOActivate();
	gpu.ShaderBind();

	gpu.GPUCompute();

	gpu.ShaderRelease();

	//glReadPixels(0, 0, width, height,GL_RGB,GL_FLOAT,result);

	gpu.FBODeactivate();

	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	gluOrtho2D(0.0, width*2, 0.0, height*2);
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
	glViewport(0, 0, width*2, height*2);

	glPolygonMode(GL_FRONT,GL_FILL);

	glEnable(GL_TEXTURE_RECTANGLE_ARB);
	glBindTexture(GL_TEXTURE_RECTANGLE_ARB,gpu.framebuffer.texList[READ]);

	glBegin(GL_QUADS);
	glTexCoord2f(0.0, 0.0); 
	glVertex2f(0.0, 0.0);
	glTexCoord2f(width, 0.0); 
	glVertex2f(width*2, 0.0);
	glTexCoord2f(width, height); 
	glVertex2f(width*2, height*2);
	glTexCoord2f(0.0, height); 
	glVertex2f(0.0, height*2);
	glEnd();

	glDisable(GL_TEXTURE_RECTANGLE_ARB);

	//glDrawPixels(width,height,GL_RGB,GL_FLOAT,result);

	glutSwapBuffers();

	gpu.Swap();

	

	glutPostRedisplay();

}

void main(int argc, char *argv[])
{
	data=(float*)malloc(width*height*3*sizeof(float));
	result=(float*)malloc(width*height*3*sizeof(float));

	for (int i=0;i<width;i++)
	{
		for (int j=0;j<height;j++)
		{
			float flip;

			if (i<width/2)
			{
				flip=0.5;
			}else{
				flip=1.0;
			}
			data[3*(i*height+j)]=data[3*(i*height+j)+1]=data[3*(i*height+j)+2]=flip;
		}
	}

	glutInit ( &argc, argv );
	glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
	glutInitWindowSize(width*2, height*2);
	glutCreateWindow("GPGPU");
	glutDisplayFunc(display);

	gpu.shaderContext=cgCreateContext();
	gpu.Load("GP_F.cg",CG_GL_FRAGMENT);

	gpu.SetUpFBO(width,height,GL_RGB32F_ARB,GL_RGB,GL_FLOAT,GL_TEXTURE_RECTANGLE_ARB);
	gpu.InitTexBuffer("data",data,result);

	glutMainLoop();

	
}